import { Layout, message } from 'antd';
import React, { Suspense, useEffect, useState } from 'react';

import useWindowWidth from '@/hooks/event/use-window-width';

import './permission.scss';

import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useParams } from '@/router/hooks';
import { useDatasetStore } from '@/store/datasetStore';
import { UserRoleEnum } from '@/common/app/constants';
import { CircleLoading } from '@/components/loading';
import { CustomMenu } from '@/components/eai-design';

// import DatasetManager from '@/pages/datasets';
// import KnowGovManager from '@/pages/know-gov';
// import ApiManager from '@/pages/api-manage';
// import ExtensionManager from '@/pages/extension-manage';
// import KnowledgeBaseApproval from '@/pages/knowledge-base-approval';
// import Connector from '@/pages/know-gov/sub-pages/connector';
// import Approval from '@/pages/know-gov/sub-pages/approval';

const DatasetManager = React.lazy(() => import('@/pages/datasets'));
const KnowGovManager = React.lazy(() => import('@/pages/know-gov'));
const ApiManager = React.lazy(() => import('@/pages/api-manage'));
const BusinessManager = React.lazy(() => import('@/pages/business-manage'));
const ExtensionManager = React.lazy(() => import('@/pages/extension-manage'));
const KnowledgeBaseApproval = React.lazy(() => import('@/pages/knowledge-base-approval'));
const Connector = React.lazy(() => import('@/pages/know-gov/sub-pages/connector'));
const Nl2sql = React.lazy(() => import('@/pages/nl2sql-manage'));
const Approval = React.lazy(() => import('@/pages/know-gov/sub-pages/approval'));
const KnowGovDataOverview = React.lazy(() => import('@/pages/know-gov/views/data-overview'));
const AiUnanswerable = React.lazy(() => import('@/pages/know-gov/views/ai-unanswerable'));
const UserDislike = React.lazy(() => import('@/pages/know-gov/views/user-dislike'));
const FreshKnowledge = React.lazy(() => import('@/pages/know-gov/views/fresh-knowledge'));
const DocumentSimilarity = React.lazy(() => import('@/pages/know-gov/views/document-similarity'));

const { Header, Content, Sider } = Layout;
// 定义知识管理子页面类型
export type KnowledgeSubPageType =
  | 'datasets'
  | 'know-gov'
  | 'api'
  | 'business'
  | 'extension'
  | 'knowledge-base-approval'
  | 'connector'
  | 'nl2sql'
  | 'approval'
  | 'data-overview'
  | 'ai-unanswerable'
  | 'user-dislike'
  | 'fresh-knowledge'
  | 'document-similarity';

// 定义组件接收的属性
interface AppPageProps {
  subPage?: KnowledgeSubPageType;
  onPageChange?: (page: KnowledgeSubPageType) => void;
  appType?: string;
}

const AppPage: React.FC<AppPageProps> = ({ subPage, onPageChange, appType }) => {
  const { appId = '' } = useParams() as { appId: string };
  const [messageApi, contextHolder] = message.useMessage();
  const [selectedKey, setSelectedKey] = useState<KnowledgeSubPageType>(subPage || 'datasets');
  const { isPc } = useWindowWidth();

  const { userRole, configurations, isInOrchestrationPage } = useOrchestrationStore();
  const { getParentId, getApprovalList, approvalCount } = useDatasetStore();

  console.log('configurations==========', configurations);

  const isEnableFunctionCalling = configurations?.find(
    (config) => config.name === 'enable_function_calling',
  );
  const { special_app_lable } = useOrchestrationStore();

  // const { fetchInitialInfo } = useConfigActions();

  const isEnableApplicationRecommend = configurations?.find(
    (config) => config.name === 'enable_application_recommend',
  );

  const isEnableNl2sql = configurations?.find((config) => config.name === 'enable_nl2sql');

  const isEnableNl2sqlDataset =
    configurations?.find((config) => config.name === 'enable_nl2sql_dataset')?.default_value ===
      '1' || false;

  const isEnableBizmateDataset =
    configurations?.find((config) => config.name === 'enable_bizmate_dataset')?.default_value ===
      '1' || false;

  // 响应外部subPage属性变化
  useEffect(() => {
    if (subPage) {
      setSelectedKey(subPage);
    }
  }, [subPage]);

  // 处理URL参数
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const appParam = searchParams.get('app');
    if (
      appParam &&
      (appParam === 'datasets' ||
        appParam === 'know-gov' ||
        appParam === 'api' ||
        appParam === 'business' ||
        appParam === 'extension' ||
        appParam === 'knowledge-base-approval' ||
        appParam === 'connector' ||
        appParam === 'nl2sql' ||
        appParam === 'data-overview' ||
        appParam === 'ai-unanswerable' ||
        appParam === 'user-dislike' ||
        appParam === 'fresh-knowledge' ||
        appParam === 'document-similarity' ||
        appParam === 'approval')
    ) {
      setSelectedKey(appParam as KnowledgeSubPageType);
    } else if (subPage) {
      setSelectedKey(subPage);
    } else {
      setSelectedKey('datasets');
    }
    // 首次获取
    // getApprovalList({
    //   page: 1,
    //   page_size: 10,
    //   offset: 0,
    //   searchText: '',
    //   app_id: appId,
    // });
  }, [location.search]);

  const handleMenuClick = (e: { key: string }) => {
    // 页面跳转的时候清空，parentId
    getParentId('');
    const key = e.key as KnowledgeSubPageType;
    setSelectedKey(key);

    // 通知父组件页面变更
    if (onPageChange) {
      onPageChange(key);
    }
  };

  const getContentComponent = () => {
    switch (selectedKey) {
      case 'datasets':
        return <DatasetManager />;
      case 'know-gov':
        return <KnowGovManager />;
      case 'api':
        return <ApiManager appType={appType} />;
      case 'business':
        return <BusinessManager />;
      case 'extension':
        return <ExtensionManager />;
      case 'knowledge-base-approval':
        return <KnowledgeBaseApproval />;
      case 'connector':
        return <Connector />;
      case 'nl2sql':
        return <Nl2sql />;
      case 'approval':
        return <Approval />;
      case 'data-overview':
        return <KnowGovDataOverview handleMenuClick={handleMenuClick} />;
      case 'ai-unanswerable':
        return <AiUnanswerable />;
      case 'user-dislike':
        return <UserDislike />;
      case 'fresh-knowledge':
        return <FreshKnowledge />;
      case 'document-similarity':
        return <DocumentSimilarity />;
      default:
        return <DatasetManager />;
    }
  };

  // 根据用户角色过滤菜单项
  const getFilteredMenuItems = () => {
    const knowledgeBaseMenu = {
      key: 'knowledge-base',
      icon: 'menu_knowledge',
      label: '知识库',
      children: [
        {
          key: 'datasets',
          icon: 'menu_file',
          label: '知识文件',
        },
        ...(!isInOrchestrationPage || isEnableFunctionCalling
          ? [
              {
                key: 'api',
                icon: 'menu_interface',
                label: '数据接口',
              },
            ]
          : []),
        ...(isInOrchestrationPage && isEnableApplicationRecommend
          ? [
              {
                key: 'extension',
                icon: 'menu_application_manage',
                label: '业务管理',
              },
            ]
          : []),
        {
          key: 'connector',
          icon: 'menu_connection',
          label: '数据同步',
        },
        ...(!isInOrchestrationPage || isEnableNl2sql || isEnableNl2sqlDataset
          ? [
              {
                key: 'nl2sql',
                icon: 'menu_nl2sql',
                label: '数据库问答',
              },
            ]
          : []),
        ...(isInOrchestrationPage && isEnableBizmateDataset
          ? [
              {
                key: 'business',
                icon: 'menu_business',
                label: '业务办理',
              },
            ]
          : []),
      ],
    };

    const knowledgeGovMenu = {
      key: 'know-gov',
      icon: 'menu_set',
      label: '知识治理',
      children: [
        {
          key: 'data-overview',
          icon: 'menu_data1',
          label: '数据总览',
        },
        {
          key: 'ai-unanswerable',
          icon: 'menu_unanswerable',
          label: 'AI未知问',
        },
        {
          key: 'user-dislike',
          icon: 'menu_dislike',
          label: '用户点踩问',
        },
        {
          key: 'fresh-knowledge',
          icon: 'menu_fresh',
          label: '知识新鲜度',
        },
        {
          key: 'document-similarity',
          icon: 'menu_similarity',
          label: '文档重复',
        },
      ],
    };

    const allMenuItems = [knowledgeBaseMenu, knowledgeGovMenu];

    switch (userRole) {
      case UserRoleEnum.admin:
        return allMenuItems;
      case UserRoleEnum.knowledge_manager:
        return allMenuItems
          .filter((item) => item.key === 'knowledge-base' || item.key === 'know-gov')
          .map((item) => {
            if (item.key === 'knowledge-base') {
              // 过滤知识库下的二级菜单
              return {
                ...item,
                children: item.children.filter((child) =>
                  ['datasets', 'connector'].includes(child.key),
                ),
              };
            }
            return item;
          });
      case UserRoleEnum.knowledge_reviewer:
        return allMenuItems
          .filter((item) => item.key === 'knowledge-base' || item.key === 'know-gov')
          .map((item) => {
            // 只保留知识文件
            return {
              ...item,
              children: item.children.filter((child) => child.key === 'datasets'),
            };
          });
      default:
        return allMenuItems;
    }
  };

  return (
    <Layout
      className="layoutborder bg-@brand-color-home [-ms-overflow-style:none] [scrollbar-width:none]"
      style={{ overflowX: 'hidden', height: '100vh' }}
    >
      {contextHolder}
      <Layout>
        <>
          <Sider
            width={true ? 260 : '100%'}
            className="!rounded-[12px]"
            style={{
              background: '#ffffff',
              display: 'flex',
              flexDirection: 'column',
              // borderInlineEnd: '1px solid rgba(13, 75, 255, 0.13)',
              // borderRadius: "12px",
              height: 'calc(100vh - 80px)',
            }}
          >
            <CustomMenu
              style={{
                height: 'calc(100vh - 140px)',
                borderRadius: '12px',
                padding: '10px',
                background: '#ffffff',
                border: 'none',
                borderInlineEnd: 'unset',
              }}
              items={getFilteredMenuItems()}
              mode="inline"
              selectedKeys={selectedKey ? [selectedKey] : []}
              onClick={handleMenuClick}
              className="knowledge-menu"
            />
          </Sider>
          <Content
            // className="ml-2 rounded-xl bg-[#ffffff]"  这个先注释掉
            className="ml-2 rounded-xl"
            style={{
              overflow: 'auto',
              height: 'calc(100vh - 80px)',
            }}
          >
            <Suspense fallback={<CircleLoading />}>{getContentComponent()}</Suspense>
          </Content>
        </>
      </Layout>
    </Layout>
  );
};

export default AppPage;
